/**
 * @desc: 新增极兔面单授权
 */
import { useState, useEffect } from 'react';
import { Input, Form, message, Cascader } from 'antd';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { layout2 } from '@/utils/config';
import { addJituAuthoriOp, updateJituOp } from '../service';
import { getAllArea } from '@/services/common';

const { TextArea } = Input;
//极兔面单授权

let areaList = [];

const FastRabbitModal = ({ visible, record, handleOk, handleCancel }) => {
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false); //loading
  const [query, setQuery] = useState({}); //详情数据回填表单
  const [details, setDetails] = useState('');

  useEffect(() => {
    getAreaList();
  }, []);

  useEffect(() => {
    if (visible && Object.keys(record).length) {
      const { extend = '{}', province, city, area } = record;
      const obj = JSON.parse(extend ? extend : '{}');
      const newQuery = {
        ...record,
        ...obj,
        extend: undefined,
      };
      if (province || city || area) {
        newQuery.cascaderAddress = [province, city, area];
      }
      setQuery(newQuery);
    } else {
      form.resetFields();
    }
  }, [visible]);

  useEffect(() => {
    form.resetFields();
  }, [query]);

  // 获取地区列表
  const getAreaList = async () => {
    const { success, data = [] } = await getAllArea();
    if (success) {
      areaList = data;
    }
  };

  const onOk = () => {
    form.validateFields().then(async (val) => {
      if (val.cascaderAddress) {
        const [province, city, area] = val.cascaderAddress;
        val = {
          province,
          city,
          area,
          ...val,
          cascaderAddress: undefined,
        };
      }
      setLoading(true);
      let res;
      if (Object.keys(record).length) {
        res = await updateJituOp({
          //更新
          ...val,
          id: record.id,
        });
      } else {
        //新增
        res = await addJituAuthoriOp(val);
      }
      const { success, msg } = res;
      if (success) {
        message.success(msg);
        handleOk();
        onCancel();
      }
      setLoading(false);
    });
  };

  const onCancel = () => {
    handleCancel();
    setQuery({});
    setDetails('');
  };

  return (
    <CommonModal
      title="极兔面单授权"
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Form
        form={form}
        name="add-fast-rabbit-auth-form"
        {...layout2}
        initialValues={{ ...query }}
      >
        <Form.Item
          name="customerCode"
          label="客户编码"
          rules={[
            { required: true, message: '客户编码不能为空' },
            { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文' },
          ]}
        >
          <Input placeholder="请输入客户编码" autoComplete="off" />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[
            { required: true, message: '客户密码不能为空' },
            { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文' },
          ]}
        >
          <Input placeholder="请输入校验码" maxLength={32} autoComplete="off" />
        </Form.Item>

        <Form.Item
          name="networkName"
          label="网点名称"
          rules={[{ required: true, message: '网点名称不能为空' }]}
        >
          <Input
            placeholder="请输入，建议与极兔合作的网点保持一致"
            maxLength={20}
            autoComplete="off"
          />
        </Form.Item>

        <Form.Item name="senderName" label="发件人">
          <Input
            placeholder="请输入寄件人，最多20个字符"
            maxLength={20}
            autoComplete="off"
          />
        </Form.Item>

        <Form.Item
          name="senderMobile"
          label="联系电话"
          rules={[{ pattern: /^[\d-]*$/, message: '仅限输入数字和“-”' }]}
        >
          <Input placeholder="请输入联系电话" autoComplete="off" />
        </Form.Item>

        <Form.Item name="cascaderAddress" label="发货地区">
          <Cascader
            options={areaList}
            fieldNames={{ label: 'name', value: 'name', children: 'childs' }}
            placeholder="请选择地区"
          />
        </Form.Item>

        <Form.Item name="detail" label="详细地址">
          <TextArea
            rows={2}
            maxLength={50}
            placeholder="请输入详细地址，最多50个字符"
            value={details}
            onChange={(e) => setDetails(e.target.value.slice(0, 50))}
          />
        </Form.Item>
      </Form>
      <CommonLoading loading={loading} />
    </CommonModal>
  );
};

export default FastRabbitModal;
